/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-use-before-define */
import type { AxiosResponse } from 'axios';
import axios from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
import FileSaver from 'file-saver';
import { useAuthStore } from '@/store/modules/auth';
import { $t } from '@/locales';
import { cookieStg, localStg } from '@/utils/storage';
import { getServiceBaseURL, getSystemParams } from '@/utils/service';
import { blobValidate } from '@/utils/common';
import { encryptBase64, encryptWithAes, generateAesKey } from '@/utils/crypto';
import { encrypt } from '@/utils/jsencrypt';
import { handleRefreshToken, showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';
const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';
const encryptHeader = 'encrypt-key';
const { baseURL, otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
const system = getSystemParams();
// 是否显示重新登录
export const isRelogin = { show: false };
let showDialog = false;
export const request = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL,
    headers: {
      // apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2',
      Clientid: system?.client_id
    }
  },
  {
    async onRequest(config) {
      const { headers } = config;
      // 是否需要加密
      const isEncrypt = headers?.isEncrypt === 'true';
      const token = cookieStg.get('smart-authorization');
      if (token && headers.withToken !== false) {
        const Authorization = token ? `Bearer ${token}` : null;
        Object.assign(headers, { Authorization });
      }
      if (import.meta.env.VITE_APP_ENCRYPT === 'true') {
        // 当开启参数加密
        if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
          // 生成一个 AES 密钥
          const aesKey = generateAesKey();
          config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
          config.data =
            typeof config.data === 'object'
              ? encryptWithAes(JSON.stringify(config.data), aesKey)
              : encryptWithAes(config.data, aesKey);
          config.headers['Content-Type'] = 'application/json';
        }
      }
      return config;
    },
    isBackendSuccess(response) {
      // 处理成功
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    async onBackendFail(response, instance) {
      const authStore = useAuthStore();

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== response.data.msg);
      }
      // when the backend response code is in `logoutCodes`, it means the user will be logged out and redirected to login page
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      if (logoutCodes.includes(String(response.data.code))) {
        handleLogout();
        return null;
      }

      // when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (
        modalLogoutCodes.includes(String(response.data.code)) &&
        !request.state.errMsgStack?.includes(response.data.msg)
      ) {
        request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.msg];
        if (!showDialog) {
          showDialog = true;
          // prevent the user from refreshing the page
          // window.addEventListener('beforeunload', handleLogout);
          setTimeout(() => {
            (window as any).$dialog?.error({
              title: 'Error',
              content: response.data.msg,
              positiveText: $t('common.confirm'),
              maskClosable: false,
              onPositiveClick() {
                showDialog = false;
                logoutAndCleanup();
              },
              onClose() {
                showDialog = false;
                logoutAndCleanup();
              }
            });
          }, 500);
        }

        return null;
      }

      // when the backend response code is in `expiredTokenCodes`, it means the token is expired, and refresh token
      // the api `refreshToken` can not return error code in `expiredTokenCodes`, otherwise it will be a dead loop, should return `logoutCodes` or `modalLogoutCodes`
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(response.data.code) && !request.state.isRefreshingToken) {
        request.state.isRefreshingToken = true;

        const refreshConfig = await handleRefreshToken(response.config);

        request.state.isRefreshingToken = false;

        if (refreshConfig) {
          return instance.request(refreshConfig) as Promise<AxiosResponse>;
        }
      }

      return null;
    },
    transformBackendResponse(response) {
      return response.data;
    },
    onError(error) {
      // eslint-disable-next-line no-debugger
      // when the request is fail, you can show error message
      let message = error.message;
      let backendErrorCode = '';

      // get backend error message and code
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
        backendErrorCode = error.response?.data?.code || '';
      }

      // the error message is displayed in the modal
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode)) {
        return;
      }

      // when the token is expired, refresh token and retry request, so no need to show error message
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(backendErrorCode)) {
        return;
      }
      if (error.response.status === 500) {
        message = '服务器错误,请联系管理员!';
      }
      showErrorMsg(request.state, message);
    }
  }
);
export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: otherBaseURL.demo
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = cookieStg.get('smart-authorization');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, { Authorization });
      // https://docker.1panel.live/
      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "200", it means the request is success
      // you can change this logic by yourself
      return response.data.status === '200';
    },
    async onBackendFail(_response) {
      // when the backend response code is not "200", it means the request is fail
      // for example: the token is expired, refresh token and retry request
    },
    transformBackendResponse(response) {
      return response.data.result;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;
      // show backend error message
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }
      (window as any).$message?.error(message);
    }
  }
);
interface DownloadOptions {
  url: string;
  dataParams: any;
  params: any;
  fileName: string;
}
// 通用下载方法
export const download = async ({ url, dataParams, params, fileName }: DownloadOptions): Promise<void> => {
  // @ts-expect-error
  const loadingInstance = window.$message.loading('正在下载数据，请稍候', { duration: 0 });
  const urlFormate = `${baseURL}/${url}`;
  try {
    const token = cookieStg.get('smart-authorization');
    const Authorization = token ? `Bearer ${token}` : null;
    const res = await axios({
      method: 'POST',
      headers: {
        Clientid: system?.client_id,
        Authorization
      },
      params,
      data: dataParams,
      url: urlFormate,
      responseType: 'blob'
    });
    if (blobValidate(res.data)) {
      const blob = new Blob([res.data], { type: 'application/octet-stream' });
      FileSaver.saveAs(blob, fileName);
      return Promise.resolve();
    }
    printErrMsg(res.data);
    return Promise.reject();
  } catch (error) {
    printErrMsg(error);
    return Promise.reject();
  } finally {
    loadingInstance.destroy();
  }
};
const printErrMsg = async (data: any) => {
  const resText = await data.text();
  const rspObj = JSON.parse(resText);
  // @ts-expect-error
  window.$message.error(rspObj.msg);
};
